package com.rms.server.Service;

import com.rms.server.DTO.DailySalesProfitDTO;
import com.rms.server.DTO.DishWithIngredientsDTO;
import com.rms.server.DTO.IngredientInfoDTO;
import com.rms.server.DTO.OrderRequest;
import com.rms.server.Dao.DishMapper;
import com.rms.server.Dao.IngredientMapper;
import com.rms.server.Dao.OrderDetailsMapper;
import com.rms.server.Dao.OrderMapper;
import com.rms.server.Domain.Dish;
import com.rms.server.Domain.Ingredient;
import com.rms.server.Domain.Order;
import com.rms.server.Domain.OrderDetails;
import com.rms.server.VO.DailySalesProfitResponse;
import com.rms.server.VO.IngredientStockChange;
import com.rms.server.VO.OrderDetailResponse;
import com.rms.server.VO.OrderResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderService {
    @Autowired
    private DishIngredientAssociationService dishIngredientAssociationService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IngredientMapper ingredientMapper;
    @Autowired
    private OrderDetailsMapper orderDetailsMapper;
    @Autowired
    private DishMapper dishMapper;
    //实现下单步骤：
    //1.前端传来菜品id和菜品数量(List<OrderRequest>)
    //2.根据菜品id找到菜品信息，判断库存是否足够
    //3.根据菜品id找到菜品的原料信息，判断原料库存是否足够
    //4.创建订单，更新库存，生成订单详情，生成利润
//    @Transactional
//    public void createOrder(List<OrderRequest> orderRequests) {
//        //总销售额度
//        BigDecimal totalPrice = BigDecimal.ZERO;
//        //利润
//        BigDecimal totalProfit = BigDecimal.ZERO;
//        for (OrderRequest orderRequest : orderRequests) {
//            DishWithIngredientsDTO dishWithIngredientsDTO = dishIngredientAssociationService.getDishWithIngredientsById(orderRequest.getDishId());
//          //  遍历遍历菜品的原料信息，检查库存
//            for (IngredientInfoDTO ingredientInfoDTO : dishWithIngredientsDTO.getIngredients()) {
//                Ingredient ingredient = ingredientMapper.selectIngredientById(ingredientInfoDTO.getIngredientId());
//                //使用的原料=每份所需*份数
//                double usedIngredient = ingredientInfoDTO.getQuantityUsed() * orderRequest.getQuantity();
//                if (ingredient.getStockQuantity() < usedIngredient) {
//                    throw new RuntimeException("库存不足，无法下单");
//                }
//            }
//        }
//        //计算总价和总利润
//        for (OrderRequest orderRequest : orderRequests) {
//            DishWithIngredientsDTO dishWithIngredientsDTO = dishIngredientAssociationService.getDishWithIngredientsById(orderRequest.getDishId());
//            Dish dish = dishMapper.selectDishById(orderRequest.getDishId());
//            //计算总价
//            // 将 quantity 转换为 BigDecimal
//            BigDecimal price = new BigDecimal(dish.getPrice());
//            totalPrice = totalPrice.add(price.multiply(new BigDecimal(orderRequest.getQuantity())));
//            // 计算菜品的总成本
//            BigDecimal totalCost = BigDecimal.ZERO;
//            for (IngredientInfoDTO ingredientInfoDTO : dishWithIngredientsDTO.getIngredients()) {
//                Ingredient ingredient = ingredientMapper.selectIngredientById(ingredientInfoDTO.getIngredientId());
//                //每份所需*份数*单价
//                BigDecimal ingredientCost = new BigDecimal(ingredientInfoDTO.getQuantityUsed()).multiply(new BigDecimal(ingredient.getUnitPrice()));
//                totalCost= totalCost.add(ingredientCost);
//            }
//            totalProfit = totalProfit.add(totalPrice.subtract(totalCost));
//            //扣减库存
//            for (IngredientInfoDTO ingredientInfoDTO : dishWithIngredientsDTO.getIngredients()) {
//                Ingredient ingredient = ingredientMapper.selectIngredientById(ingredientInfoDTO.getIngredientId());
//                //使用的原料=每份所需*份数
//                double usedIngredient = ingredientInfoDTO.getQuantityUsed() * orderRequest.getQuantity();
//                ingredientMapper.updateStock(ingredient.getIngredientId(), -usedIngredient);
//            }
//        }
//        //创建订单
//        Order order = new Order();
//        order.setOrderDate(String.valueOf(LocalDateTime.now()));
//        order.setTotalPrice(totalPrice);
//        order.setTotalProfit(totalProfit);
//        orderMapper.insertOrder(order);
//        Long orderId = order.getOrderId();
//        // 创建订单详情
//        for (OrderRequest orderRequest : orderRequests) {
//            Dish dish = dishMapper.selectDishById(orderRequest.getDishId());
//            OrderDetails orderDetails = new OrderDetails();
//            orderDetails.setOrderId(orderId);  // 确保 orderId 设置正确
//            orderDetails.setDishId(dish.getDishId());
//            orderDetails.setQuantity(orderRequest.getQuantity());
//            orderDetails.setDishPrice(BigDecimal.valueOf(dish.getPrice()));
//
//            // 计算每个订单项的单独利润
//            BigDecimal price = new BigDecimal(dish.getPrice());
//            BigDecimal totalCost = BigDecimal.ZERO;
//            DishWithIngredientsDTO dishWithIngredientsDTO = dishIngredientAssociationService.getDishWithIngredientsById(orderRequest.getDishId());
//            for (IngredientInfoDTO ingredientInfoDTO : dishWithIngredientsDTO.getIngredients()) {
//                Ingredient ingredient = ingredientMapper.selectIngredientById(ingredientInfoDTO.getIngredientId());
//                BigDecimal ingredientCost = new BigDecimal(ingredientInfoDTO.getQuantityUsed()).multiply(new BigDecimal(ingredient.getUnitPrice()));
//                totalCost = totalCost.add(ingredientCost);
//            }
//
//            // 每个订单项的利润
//            BigDecimal dishProfit = price.multiply(new BigDecimal(orderRequest.getQuantity())).subtract(totalCost);
//            orderDetails.setProfit(dishProfit);
//
//            orderDetailsMapper.insertOrderDetails(orderDetails);
//        }
//    }
    @Transactional
    public OrderResponse createOrder(List<OrderRequest> orderRequests) {
        // 初始化总价、总利润、订单详情列表和库存变化列表
        BigDecimal totalPrice = BigDecimal.ZERO;  // 总价初始化为0
        BigDecimal totalProfit = BigDecimal.ZERO;  // 总利润初始化为0
        List<OrderDetailResponse> orderDetailResponses = new ArrayList<>();  // 订单详情列表
        List<IngredientStockChange> stockChanges = new ArrayList<>();  // 库存变化记录列表

        // 检查库存：确保每个菜品的原料库存足够
        for (OrderRequest orderRequest : orderRequests) {
            // 获取菜品及其所需原料的详细信息
            DishWithIngredientsDTO dishWithIngredientsDTO = dishIngredientAssociationService.getDishWithIngredientsById(orderRequest.getDishId());
            for (IngredientInfoDTO ingredientInfoDTO : dishWithIngredientsDTO.getIngredients()) {
                // 根据原料ID查询原料的库存信息
                Ingredient ingredient = ingredientMapper.selectIngredientById(ingredientInfoDTO.getIngredientId());
                // 计算本次订单中使用的该原料的数量
                BigDecimal usedIngredient = BigDecimal.valueOf(ingredientInfoDTO.getQuantityUsed() * orderRequest.getQuantity());
                // 如果原料库存不足，抛出异常，提示库存不足无法下单
                if (ingredient.getStockQuantity().compareTo(new BigDecimal(String.valueOf(usedIngredient))) < 0) {
                    throw new RuntimeException("库存不足，无法下单");
                }
            }
        }

        // 计算订单的总价和总利润
        for (OrderRequest orderRequest : orderRequests) {
            // 获取菜品及其所需原料的详细信息
            DishWithIngredientsDTO dishWithIngredientsDTO = dishIngredientAssociationService.getDishWithIngredientsById(orderRequest.getDishId());
            Dish dish = dishMapper.selectDishById(orderRequest.getDishId());

            // 累加菜品的价格到总价中
            BigDecimal price = BigDecimal.valueOf(dish.getPrice());
            totalPrice = totalPrice.add(price.multiply(new BigDecimal(orderRequest.getQuantity())));

            // 计算菜品的总成本
            BigDecimal totalCost = BigDecimal.ZERO;
            for (IngredientInfoDTO ingredientInfoDTO : dishWithIngredientsDTO.getIngredients()) {
                Ingredient ingredient = ingredientMapper.selectIngredientById(ingredientInfoDTO.getIngredientId());
                // 计算每种原料的成本
                BigDecimal ingredientCost = new BigDecimal(ingredientInfoDTO.getQuantityUsed()).multiply(new BigDecimal(ingredient.getUnitPrice()));
                totalCost = totalCost.add(ingredientCost);  // 累加到总成本
            }

            // 计算每个菜品的利润，并累加到总利润中
            BigDecimal dishProfit = (price.subtract(totalCost)).multiply(new BigDecimal(orderRequest.getQuantity()));
            totalProfit = totalProfit.add(dishProfit);

            // 更新库存并记录库存变化
            for (IngredientInfoDTO ingredientInfoDTO : dishWithIngredientsDTO.getIngredients()) {
                Ingredient ingredient = ingredientMapper.selectIngredientById(ingredientInfoDTO.getIngredientId());
                // 计算本次订单使用的原料数量
                double usedIngredient = ingredientInfoDTO.getQuantityUsed() * orderRequest.getQuantity();
                // 更新库存
                ingredientMapper.updateStock(ingredient.getIngredientId(), usedIngredient);

                // 记录库存变化
                IngredientStockChange stockChange = new IngredientStockChange();
                stockChange.setIngredientId(ingredient.getIngredientId());
                stockChange.setIngredientName(ingredient.getIngredientName());
                stockChange.setStockBefore(ingredient.getStockQuantity());  // 变更前的库存量
                BigDecimal usedIngredientBigDecimal = new BigDecimal(usedIngredient);  // 将使用的原料数量转换为BigDecimal
                BigDecimal stockAfter = ingredient.getStockQuantity().subtract(usedIngredientBigDecimal);  // 计算变更后的库存量
                stockChange.setStockAfter(stockAfter);
                stockChange.setQuantityUsed(BigDecimal.valueOf(usedIngredient));  // 使用的原料数量
                stockChanges.add(stockChange);  // 将库存变化记录加入到列表
            }

            // 创建订单详情
            OrderDetailResponse orderDetailResponse = new OrderDetailResponse();
            orderDetailResponse.setDishId(dish.getDishId());  // 设置菜品ID
            orderDetailResponse.setQuantity(orderRequest.getQuantity());  // 设置菜品数量
            orderDetailResponse.setDishPrice(BigDecimal.valueOf(dish.getPrice()));  // 设置菜品单价
            orderDetailResponse.setProfit(dishProfit);  // 设置该菜品的利润
            orderDetailResponses.add(orderDetailResponse);  // 将订单详情加入到列表中
        }

        // 创建订单实体，并保存到数据库
        Order order = new Order();
        order.setOrderDate(LocalDateTime.parse(String.valueOf(LocalDateTime.now())));  // 设置订单日期为当前时间
        order.setTotalPrice(totalPrice);  // 设置订单总价
        order.setTotalProfit(totalProfit);  // 设置订单总利润
        orderMapper.insertOrder(order);  // 将订单插入到数据库中
        Long orderId = order.getOrderId();  // 获取生成的订单ID

        // 创建订单详情记录并保存到数据库
        for (OrderDetailResponse orderDetailResponse : orderDetailResponses) {
            OrderDetails orderDetails = new OrderDetails();
            orderDetails.setOrderId(orderId);  // 设置订单ID
            orderDetails.setDishId(orderDetailResponse.getDishId());  // 设置菜品ID
            orderDetails.setQuantity(orderDetailResponse.getQuantity());  // 设置菜品数量
            orderDetails.setDishPrice(orderDetailResponse.getDishPrice());  // 设置菜品单价
            orderDetails.setProfit(orderDetailResponse.getProfit());  // 设置菜品的利润
            orderDetailsMapper.insertOrderDetails(orderDetails);  // 将订单详情插入到数据库中
        }

        // 创建并返回包含订单信息、订单详情和库存变化的响应
        OrderResponse orderResponse = new OrderResponse();
        orderResponse.setOrderId(order.getOrderId());  // 设置订单ID
        orderResponse.setOrderDate(LocalDateTime.parse(String.valueOf(order.getOrderDate())));  // 设置订单日期
        orderResponse.setTotalPrice(totalPrice);  // 设置订单总价
        orderResponse.setTotalProfit(totalProfit);  // 设置订单总利润
        orderResponse.setOrderDetails(orderDetailResponses);  // 设置订单详情
        orderResponse.setStockChanges(stockChanges);  // 设置库存变化记录
        return orderResponse;  // 返回订单响应
    }
    //计算每日销售额和利润
//    public List<DailySalesProfitResponse> calculateSalesAndProfit(LocalDateTime startDate, LocalDateTime endDate) {
//        // 获取指定日期范围内的所有订单数据
//        List<Order> orders = orderMapper.selectOrdersByDateRange(startDate, endDate);
//        // 用于存储每天的销售额和利润
//        Map<String, DailySalesProfitDTO> dailySalesProfitMap = new HashMap<>();
//        BigDecimal totalSales = BigDecimal.ZERO;
//        BigDecimal totalProfit = BigDecimal.ZERO;
//        // 遍历订单数据，计算每天的销售额和利润
//        for (Order order : orders) {
//            String orderDate = String.valueOf(order.getOrderDate());
//            // 如果当天没有记录，就初始化一个新的DTO对象
//            DailySalesProfitDTO dailySalesProfitDTO = dailySalesProfitMap.getOrDefault(orderDate, new DailySalesProfitDTO());
//            // 累加当天的销售额和利润
//            dailySalesProfitDTO.setDailySales(dailySalesProfitDTO.getDailySales().add(order.getTotalPrice()));
//            dailySalesProfitDTO.setDailyProfit(dailySalesProfitDTO.getDailyProfit().add(order.getTotalProfit()));
//            // 将更新后的DTO对象重新存入Map
//            dailySalesProfitMap.put(orderDate, dailySalesProfitDTO);
//            // 累加总销售额和总利润
//            totalSales = totalSales.add(order.getTotalPrice());
//            totalProfit = totalProfit.add(order.getTotalProfit());
//        }
//        // 创建 DailySalesProfitResponse 用于返回每日数据
//        List<DailySalesProfitResponse> responseList = new ArrayList<>();
//        // 遍历所有日期，将每个日期的 sales 和 profit 封装成一个 response 对象
//        for (Map.Entry<String, DailySalesProfitDTO> entry : dailySalesProfitMap.entrySet()) {
//            DailySalesProfitResponse response = new DailySalesProfitResponse();
//            response.setTotalSales(totalSales);  // 总销售额
//            response.setTotalProfit(totalProfit); // 总利润
//            response.setDailySalesProfitList(new ArrayList<>(dailySalesProfitMap.values())); // 每日数据
//            // 添加到响应列表
//            responseList.add(response);
//        }
//        return responseList; // 返回列表类型的响应
//    }
    public DailySalesProfitResponse calculateSalesProfit(LocalDate startDate, LocalDate endDate) {
        // 将日期转换为 LocalDateTime，确保时间范围包括开始和结束的整天
        LocalDateTime startDateTime = startDate.atStartOfDay(); // 开始时间：00:00:00
        LocalDateTime endDateTime = endDate.atTime(23, 59, 59); // 结束时间：23:59:59

        // 获取指定日期范围内的订单数据
        List<DailySalesProfitDTO> dailySalesProfitList = orderMapper.findSalesProfitByDateRange(startDateTime, endDateTime);

        BigDecimal totalSales = BigDecimal.ZERO;
        BigDecimal totalProfit = BigDecimal.ZERO;

        // 计算总销售额和总利润
        for (DailySalesProfitDTO dailySalesProfit : dailySalesProfitList) {
            totalSales = totalSales.add(dailySalesProfit.getDailySales());
            totalProfit = totalProfit.add(dailySalesProfit.getDailyProfit());
        }

        // 将结果包装到响应对象中
        DailySalesProfitResponse response = new DailySalesProfitResponse();
        response.setTotalSales(totalSales);
        response.setTotalProfit(totalProfit);
        response.setDailySalesProfitList(dailySalesProfitList);

        return response;
    }

}
